package com.tssup.fesco.service.impl;

import com.tssup.fesco.common.constants.ErrorStatusConstants;
import com.tssup.fesco.common.exeception.ParameterException;
import com.tssup.fesco.common.utils.DateUtils;
import com.tssup.fesco.sales.goods.persistent.mapper.RSalesStatusMapper;
import com.tssup.fesco.sales.goods.persistent.mapper.RSupplierGoodsMapper;
import com.tssup.fesco.sales.goods.persistent.pojo.RSalesStatus;
import com.tssup.fesco.sales.organization.persistent.mapper.RSupplierMapper;
import com.tssup.fesco.sales.organization.vo.QueryRSupplierVo;
import com.tssup.fesco.service.OdcSupplierService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author shuchang.liao
 * @create 2017-03-17 17:35
 */
@Service
public class OdcSupplierServiceImpl implements OdcSupplierService {

    @Autowired
    private RSupplierMapper rSupplierMapper;

    @Autowired
    private RSalesStatusMapper rSalesStatusMMapper;

    @Autowired
    private RSupplierGoodsMapper rSupplierGoodsMapper;

    @Override
    @Transactional
    public int downRGoodsBySupplierOutDate() {
        String lastDay= DateUtils.lastDay(new Date());
        QueryRSupplierVo queryRSupplierVo=new QueryRSupplierVo();
        queryRSupplierVo.setsOpdate(lastDay);
        queryRSupplierVo.seteOpdate(lastDay);
        //查询上一天所有正常状态且合同期为上一天截至的供应商id
        List<Integer> supplierIds=rSupplierMapper.selectLastDayInfos(queryRSupplierVo);
        if ( CollectionUtils.isNotEmpty(supplierIds)){
            //修改供应商状态为洽谈中
            for (Integer i:supplierIds){
                if (rSupplierMapper.updateStatusBySupplierId(i)<1) {
                    throw new ParameterException(ErrorStatusConstants.UPDATE_ERROR_CODE, ErrorStatusConstants.UPDATE_ERROR_MSG);
                }
            }
            List<RSalesStatus> skuIds=rSupplierGoodsMapper.selectUpBySupplierIds(supplierIds);
            if (CollectionUtils.isNotEmpty(skuIds)){
                //更新上架商品状态为下架
                if (rSalesStatusMMapper.updateBySkuIds(skuIds)<1) {
                    throw new ParameterException(ErrorStatusConstants.UPDATE_ERROR_CODE, ErrorStatusConstants.UPDATE_ERROR_MSG);
                }
            }
        }
        return 1;
    }
}
